<template>
  <el-card
    class="column-left"
    ref="elCardRef"
    @contextmenu.prevent="handleContextMenu"
  >
    <el-row class="center-header" justify="center">
      <div>
        <svg-icon
          v-for="(item, index) in leftToolothre"
          :title="item.label"
          class-name="iconfont"
          @click="handleClick(index)"
          :key="item.id"
          :icon-class="item.icon"
        />
      </div>
      <el-divider />
      <div>
        <svg-icon
          v-for="(item, index) in leftTool"
          :title="item.label"
          class-name="iconfont"
          @click="handleClickTool(index)"
          :key="item.id"
          :icon-class="item.icon"
        />
      </div>
    </el-row>
    <div ref="mapRef" id="map"></div>
  </el-card>
  <ContextMenu
    :menuItems="componentAMenuItems"
    v-model:visible="menuFlag"
    ref="contextMenuRef"
  />
  <autoDialog
    title="模态窗口"
    @close="flag = false"
    :isAbsolute="true"
    v-if="flag"
  >
   <MtWindow />
  </autoDialog>
  <fixed-dialog
    title="非模态窗口"
    @close="noFlag = false"
    :isAbsolute="true"
    :isScreen="false"
    v-if="noFlag"
  >
    <MtWindow />
  </fixed-dialog>
</template>

<script setup>
import { nextTick, onUnmounted, watch } from "vue";
import ContextMenu from "../common/ContextMenu.vue";
import MtWindow from './模态窗口/index.vue';


import "ol/ol.css"; // ol提供的css样式（必须引入）
import Map from "ol/Map.js";
import OSM from "ol/source/OSM.js";
import TileLayer from "ol/layer/WebGLTile.js";
import TileWMS from "ol/source/TileWMS.js";
import View from "ol/View.js";
import { TileArcGISRest, XYZ, ImageTile } from "ol/source.js";
import { fromLonLat } from "ol/proj";
import { useXmapStore } from "../../../store/modules/xmap";
// 使用 Pinia Store
const xmapStore = useXmapStore();
const mapRef = ref(null);
const menuFlag = ref(false);
const flag = ref(false);
const noFlag = ref(false);
//右键列表菜单
var map=null;
const allLayers=[];

function initMap() {
  var wmsSource = new TileWMS({
    url: "http://localhost:8888/postmap/wms",
    params: { LAYERS: "geo_hl07_line,geo_cun_point", TILED: true },
    serverType: "geoserver",
    // Countries have transparency, so do not fade tiles:
    transition: 0,
  });
  // const layer =  new TileLayer({
  //   id: 'ditu-1',
  //   source: new XYZ({
  //     // projection: projection,
  //     url: `http://localhost:8888/postmap/TileServer?T=img_w&tk=&x={x}&y={y}&z={z}`,
  //     crossOrigin: 'anonymous',
  //     wrapX: false
  //   })
  // })
  const layers = [
    new TileLayer({
      id: "ditu-1",
      source: new XYZ({
        url: "http://wprd0{1-4}.is.autonavi.com/appmaptile?lang=zh_cn&size=1&style=7&x={x}&y={y}&z={z}",
        crossOrigin: "anonymous",
        wrapX: false,
      }),
    }),
    // layer,
    // new TileLayer({
    //   extent: [-13884991, 2870341, -7455066, 6338219],
    //   source: new TileWMS({
    //     url: "https://ahocevar.com/geoserver/wms",
    //     params: { LAYERS: "topp:states", TILED: true },
    //     serverType: "geoserver",
    //     // Countries have transparency, so do not fade tiles:
    //     transition: 0,
    //   }),
    // }),
    // new TileLayer({
    //   //extent: [-13884991, 2870341, -7455066, 6338219],
    //   source: wmsSource,
    // }),
  ];
  var view = new View({
    center: fromLonLat([108.0, 34]), // 经度 10.10, 纬度 15.0
    zoom: 10,
  });
    map = new Map({
    layers: layers,
    target: "map",
    view: view,
  });

  map.on("singleclick", function (evt) {
    // document.getElementById("info").innerHTML = "";
    const viewResolution = view.getResolution();
    const url = wmsSource.getFeatureInfoUrl(
      evt.coordinate,
      viewResolution,
      "EPSG:3857",
      { INFO_FORMAT: "text/html" }
    );
    if (url) {
      fetch(url)
        .then((response) => response.text())
        .then((html) => {
          // document.getElementById("info").innerHTML = html;

          console.info(html);
        });
    }
  });
}
onMounted(() => {
  initMap();
  //不要在这写Bus.on，在busEventsDict中增加！！！！！！！！！！
});

const addLayer=(e)=>{
   var datasource= addWMSLayer(e);
   var layer= new TileLayer({
      //extent: [-13884991, 2870341, -7455066, 6338219],
      source: datasource,
    });
    map.addLayer(layer);
}

const addXYZLayer=(e)=>{}
const addWMSLayer=(e)=>{
    var wmsSource = new TileWMS({
    url: "http://localhost:8888/postmap//wms",
    params: { LAYERS: "geo_cun_point"},
    serverType: "geoserver",
    // Countries have transparency, so do not fade tiles:
    transition: 0,
  });
  return wmsSource;
}
const addWMTSLayer=(e)=>{};



const componentAMenuItems = [
  {
    label: "模态窗口",
    icon: "huanjingshezhi",
    divider: true,
    cb: () => {
      flag.value = true;
    },
  },
  {
    label: "非模态窗口",
    icon: "huanjingshezhi",
    cb: () => {
      noFlag.value = true;
    },
  },
];
//左侧工具栏状态
const leftToolStatus = ref(-1);
const leftToolothreStatus = ref(-1);
//左侧工具栏
const leftTool = [
  {
    id: 1,
    icon: "juleifenbu",
    label: "聚类分布",
  },
  {
    id: 2,
    icon: "leixingzhuanhuan",
    label: "类型转换",
  },
];
//左侧工具栏
const leftToolothre = [
  {
    id: 3,
    icon: "camera",
    label: "相机",
  },
  {
    id: 4,
    icon: "data-view",
    label: "图表",
  },
];

const handleClickTool = (index) => {
  leftToolothreStatus.value = -1;
  leftToolStatus.value = index;
  alert("点击事件");
};

const handleClick = (index) => {
  leftToolStatus.value = -1;
  leftToolothreStatus.value = index;
  alert("点击事件" + index);
};

const contextMenuRef = ref(null);
//获取鼠标位置
const handleContextMenu = (event) => {
  // 阻止默认的右键菜单行为
  event.preventDefault();

  // 获取右键菜单组件实例并设置其显示位置为鼠标点击位置
  const context = contextMenuRef.value;
  menuFlag.value = true;
  let x = event.clientX;
  let y = event.clientY;

  // 获取页面可视区域的宽度和高度
  const pageWidth = document.documentElement.clientWidth;
  const pageHeight = document.documentElement.clientHeight;
  nextTick(() => {
    // 获取右键菜单自身的宽度和高度（这里假设右键菜单已经渲染完成，可以获取到准确的尺寸）
    const menuWidth = context.$el.offsetWidth;
    const menuHeight = context.$el.offsetHeight;
    // 判断右键菜单是否超出页面右侧边界，如果超出则将其左侧位置调整为边界内
    if (x + menuWidth > pageWidth) {
      x = pageWidth - menuWidth;
    }

    // 判断右键菜单是否超出页面底部边界，如果超出则将其顶部位置往上调整
    if (y + menuHeight > pageHeight) {
      y = Math.max(0, y - menuHeight);
    }

    context.$el.style.left = x + "px";
    context.$el.style.top = y + "px";
  });
};
const elCardRef = ref(null);
const isDOM = (e) => {
  e.preventDefault();
  const target = e.target;
  var isUnderTopElement = elCardRef.value.$el.contains(target);
  if (!isUnderTopElement) {
    menuFlag.value = false;
  }
};
const wClick = (e) => {
  const target = e.target;
  const toolA = contextMenuRef.value.$el;
  const isInsideTool = toolA && toolA.contains(target);
  if (!isInsideTool) {
    menuFlag.value = false;
  }
};
onMounted(() => {
  window.addEventListener("click", wClick);
  // 监听整个窗口的右键点击事件
  window.addEventListener("contextmenu", isDOM);
});
onUnmounted(() => {
  window.removeEventListener("click", wClick);
  window.removeEventListener("contextmenu", isDOM);
});
// 监听 xmap 对象的变化
watch(  () => xmapStore.xmap,  (newXmap, oldXmap) => {
    console.log("xmap changed:", newXmap);
    // 可以在这里执行额外的操作，例如触发通知，或者更新其他部分的状态
    addLayer(newXmap)
  },
  { deep: true }
);
</script>

<style lang="scss" scoped>
.iconfont {
  width: 24px;
  height: 24px;
  font-size: 24px;
  cursor: pointer;
}

.active {
  color: #21a3f1;
}

.center-header {
  width: 40px;
  position: absolute;
  top: 5px;
  right: 5px;
  z-index: 9;
  height: 400px;
  border: 1px solid rgba(186, 186, 186, 0.6509803922);
  border-radius: 4px 0 0 4px;
  align-items: center;
  box-shadow: 0px 0px 12px rgba(0, 0, 0, 0.12);
  justify-content: start;
  display: flex;
  flex-direction: column;
  padding: 20px 0;
  box-sizing: border-box;
  overflow: auto;
  flex-wrap: nowrap;
  background-color: #fff;

  div {
    display: flex;
    flex-direction: column;

    span {
      margin-top: 10px;
    }
  }
}

.column-left {
  width: 100%;
  height: 100%;
  position: relative;
}

:deep(.el-card__body) {
  height: calc(100%);
  padding: 0 !important;
}

#map {
  height: 100%;
}

* {
  stroke: #333333, symbol("shape://vertline");
  stroke-width: 3px;

  :nth-stroke(2) {
    size: 12;
    stroke: #333333;
    stroke-width: 1px;
  }
}
</style>
